package com.example.nacosclientzuul.biz;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.example.nacosclientzuul.locator.NewZuulRouteLocator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.RoutesRefreshedEvent;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties.ZuulRoute;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.Executor;

@Component
@Slf4j
public class PropertiesAssemble {
    @Autowired
    private ApplicationEventPublisher publisher;
    @Autowired
    private NewZuulRouteLocator locator;
    public Map<String, ZuulRoute> getProperties(){
        Map<String, ZuulRoute> routeMap = new LinkedHashMap<>();
        List<ZuulRoute> routes = listenerNacos("zuul-server", "zuul-route");
        for (ZuulRoute res : routes){
            if (StringUtils.isBlank(res.getPath())) continue;
            ZuulRoute zuulRoute = new ZuulRoute();
            BeanUtils.copyProperties(res, zuulRoute);
            routeMap.put(zuulRoute.getPath(), zuulRoute);
        }
        return routeMap;
    }


    private List<ZuulRoute> listenerNacos(String dataId, String group){
        try {
            Properties properties = new Properties();
            properties.put(PropertyKeyConst.SERVER_ADDR, "148.70.142.97:8848");
                ConfigService configService = NacosFactory.createConfigService(properties);
                String content = configService.getConfig(dataId, group, 5000);
                log.info("从Nacos返回的配置：{}", content);
                configService.addListener(dataId, group, new Listener() {
                    @Override
                    public Executor getExecutor() {
                        return null;
                    }

                    @Override
                    public void receiveConfigInfo(String s) {
                        log.info("更新配置:{}", s);
                        RoutesRefreshedEvent routesRefreshedEvent = new RoutesRefreshedEvent(locator);
                        publisher.publishEvent(routesRefreshedEvent);
                    }
                });

                return JSONObject.parseArray(content, ZuulRoute.class);
            } catch (NacosException e) {
                e.printStackTrace();
            }
        return new ArrayList<>();
    }
}
